<template>
    <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="维修负责人">
            <el-input v-model="form.repairName" placeholder="维修负责人" clearable />
        </el-form-item>
        <el-form-item label="维修日期">
            <el-date-picker v-model="form.RepairTime" type="date" placeholder="维修日期" clearable format="YYYY/MM/DD"
                value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="车牌号">
            <el-input v-model="form.RepairBrand" placeholder="车牌号" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="GetRepair">查询</el-button>
            <el-button @click="onSubmit">重置</el-button>
            <el-button type="primary" @click="Updaterepaoir">新增</el-button>
            <el-button type="primary" @click="PiDeleteId">删除</el-button>
        </el-form-item>
    </el-form>
    <!-- <input type="file" @change="handleFileUpload"  > -->

    <input type="file" @change="importExcel">
    <div v-if="excelData.length > 0">
        <p v-for="(row, index) in excelData" :key="index">{{ row }}</p>
    </div>
    <button @click="exportExcel">导出Excel</button>

    <el-table :data="repairList" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column prop="repairTitle" label="维修标题" width="90px" />
        <el-table-column prop="repairType" label="维修类型" width="90px" />
        <el-table-column prop="repairBrand" label="车牌号" width="90px" />
        <el-table-column prop="repairPrice" label="维修金额" width="90px" />
        <el-table-column prop="repairName" label="维修负责人" width="100px" />
        <el-table-column prop="repairDesc" label="维修描述" width="120px" />
        <el-table-column prop="repairTime" label="维修日期" width="100px">
            <template #default="scope">
                {{ scope.row.repairTime }}
            </template>
        </el-table-column>
        <el-table-column prop="repairRemark" label="备注" width="70px" />
        <el-table-column prop="createDate" label="创建时间" width="100px">
            <template #default="scope">
                {{ scope.row.createDate }}
            </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
            <template #default="scope">
                <el-button type="primary" @click="RepairId(scope.row.repairId)">编辑</el-button>
                <el-button type="primary" @click="DeleteId(scope.row.repairId)">删除</el-button>
                <el-button type="primary" @click="repairInfoid(scope.row.repairId)">查看</el-button>
            </template>
        </el-table-column>
    </el-table>

    <table>
        <tr>
            <td>
                <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                    :page-sizes="[2, 3, 4, 5]" :background="true" prev-text="上一页" next-text="下一页"
                    layout="total,slot, sizes" :total="page.tatolCount">

                </el-pagination>
            </td>
            <td>
                <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                    :page-sizes="[2, 3, 4, 5]" :background="true" prev-text="上一页" next-text="下一页"
                    layout=" slot, prev, pager, next" :total="page.tatolCount">
                    <el-button type="primary" :disabled="page.pageIndex == 1" @click="page.pageIndex = 1">首页</el-button>
                </el-pagination>
            </td>
            <td>
                <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                    :page-sizes="[2, 3, 4, 5]" :background="true" prev-text="上一页" next-text="下一页" layout="slot,jumper"
                    :total="page.tatolCount">
                    <el-button type="primary" :disabled="page.pageIndex == page.totalPage"
                        @click="page.pageIndex = page.totalPage">尾页</el-button>
                </el-pagination>
            </td>
        </tr>
    </table>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue'
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus'
const router = useRouter();
const route = useRoute();
import * as XLSX from 'xlsx';

const form = reactive({
    repairName: "",
    RepairTime: "",
    RepairBrand: "",
})
const page = reactive({
    pageIndex: 1,
    pageSize: 2,
    tatolCount: 0,
    totalPage: 0,
})

const repairList = ref([])
watch(page, () => {
    GetRepair()
})
//维修显示
const GetRepair = () => {
    axios.get("http://47.96.140.177:8000/ReadMaintent/api/Repairs/GetRepairs", {
        params: {
            pageIndex: page.pageIndex,
            pageSize: page.pageSize,
            repairName: form.repairName,
            RepairTime: form.RepairTime,
            RepairBrand: form.RepairBrand
        }
    })
        .then(res => {
            repairList.value = res.data.data.plist
            page.tatolCount = res.data.data.tatolCount
            page.totalPage = res.data.data.totalPage
        })
}
const multipleSelection = ref([])
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
}

const Updaterepaoir = () => {
    router.push({
        name: "RepairAdd"
    })
}


const RepairId = (id: number) => {
    router.push({
        name: "UpdateRepait",
        query: {
            id: id
        }
    })
}
const repairInfoid = (id: number) => {
    router.push({
        name: "RepairInfo",
        query: {
            id: id
        }
    })
}
//单删
const DeleteId = (id: any) => {
    ElMessageBox.confirm(
        '你确定要删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("/Maintent/api/Maintain/DeleteRepairs",{
                id:id,
                deleteName:null
            })
                .then(res => {
                    if (res.data.data > 0) {
                        ElMessage.success("删除成功")
                        GetRepair()
                    }
                    else {
                        ElMessage.error("删除失败")
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

const RepairIdList = ref([])
//批量删除
const PiDeleteId = () => {

    multipleSelection.value.forEach((a: any) => {
        RepairIdList.value.push(a.repairId)
    })
    console.log(RepairIdList.value)

    ElMessageBox.confirm(
        '你确定要删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("/Maintent/api/Maintain/PiDeleteRepairs", {
                id: RepairIdList.value
            })
                .then(res => {
                    if (res.data.data > 0) {
                        ElMessage.success("删除成功")
                        GetRepair()
                    }
                    else {
                        ElMessage.error("删除失败")
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

onMounted(() => {
    GetRepair()
})
const onSubmit = () => {
    form.repairName = ""
    form.RepairTime = ""
    form.RepairBrand = ""
}

//导入
    const excelData = ref([]);
    const importExcel = (e:any) => {
      const file = e.target.files[0];
      const reader = new FileReader();
      reader.onload = (event) => {
        const data = new Uint8Array(event.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        excelData.value = jsonData;
      };
      reader.readAsArrayBuffer(file);
    }
// const handleFileUpload = (e:any) => {
//   const file = e.target.files[0];
//   if (file) {
//     const reader = new FileReader();
//     reader.onload = (event:any) => {
//       const data = new Uint8Array(event.target.result);
//       const workbook = XLSX.read(data, { type: 'array' });
//       const sheetName = workbook.SheetNames[0];
//       const worksheet = workbook.Sheets[sheetName];
//       const jsonData = XLSX.utils.sheet_to_json(worksheet);
//       console.log(jsonData);
//     };
//     reader.readAsArrayBuffer(file);
//   }
// };
// 模拟一些表格数据，实际中可以是从接口获取等方式得到的数据

//导出

const exportExcel = () => {
    const worksheet = XLSX.utils.json_to_sheet(multipleSelection.value);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const fileName = '维修导出数据.xlsx';
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
};
</script>